package cn.graydove.bot.service.impl;

import cn.graydove.bot.model.entity.QqGroup;
import cn.graydove.bot.repository.AccountRepository;
import cn.graydove.bot.repository.GroupRepository;
import cn.graydove.bot.model.dto.AccountDTO;
import cn.graydove.bot.model.entity.Account;
import cn.graydove.bot.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    private GroupRepository groupRepository;

    private AccountRepository accountRepository;

    public AccountServiceImpl(GroupRepository groupRepository, AccountRepository accountRepository) {
        this.groupRepository = groupRepository;
        this.accountRepository = accountRepository;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public String register(AccountDTO accountDTO) {
        if (groupRepository.existsByGroupNumber(accountDTO.getQqGroup())) {
            return "QQ群已存在";
        }
        if (accountRepository.existsByPhoneOrQqNumber(accountDTO.getPhone(), accountDTO.getQqNumber())) {
            return "账户已存在";
        }

        Account account = new Account(accountDTO.getPhone(), accountDTO.getQqNumber());
        account = accountRepository.save(account);

        QqGroup group = new QqGroup(account, accountDTO.getQqGroup());
        groupRepository.save(group);

        return "OK";
    }

    @Override
    public List<Account> findAll() {
        return accountRepository.findAll();
    }
}
